import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export interface AppState {
  loading: boolean
  sidebarCollapsed: boolean
  theme: 'light' | 'dark'
  language: string
  breadcrumbs: Array<{
    name: string
    path?: string
  }>
}

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const sidebarCollapsed = ref(false)
  const theme = ref<'light' | 'dark'>('dark')
  const language = ref('zh-CN')
  const breadcrumbs = ref<Array<{ name: string; path?: string }>>([])
  
  // 计算属性
  const isDarkTheme = computed(() => theme.value === 'dark')
  
  // 操作
  const setLoading = (value: boolean) => {
    loading.value = value
  }
  
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    localStorage.setItem('sidebarCollapsed', String(sidebarCollapsed.value))
  }
  
  const setSidebarCollapsed = (collapsed: boolean) => {
    sidebarCollapsed.value = collapsed
    localStorage.setItem('sidebarCollapsed', String(collapsed))
  }
  
  const setTheme = (newTheme: 'light' | 'dark') => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
    
    // 更新HTML类名
    const html = document.documentElement
    if (newTheme === 'dark') {
      html.classList.add('dark')
    } else {
      html.classList.remove('dark')
    }
  }
  
  const setLanguage = (lang: string) => {
    language.value = lang
    localStorage.setItem('language', lang)
  }
  
  const setBreadcrumbs = (crumbs: Array<{ name: string; path?: string }>) => {
    breadcrumbs.value = crumbs
  }
  
  const addBreadcrumb = (crumb: { name: string; path?: string }) => {
    breadcrumbs.value.push(crumb)
  }
  
  const clearBreadcrumbs = () => {
    breadcrumbs.value = []
  }
  
  // 初始化
  const initializeApp = () => {
    // 从localStorage恢复状态
    const savedSidebarState = localStorage.getItem('sidebarCollapsed')
    if (savedSidebarState !== null) {
      sidebarCollapsed.value = savedSidebarState === 'true'
    }
    
    const savedTheme = localStorage.getItem('theme') as 'light' | 'dark'
    if (savedTheme) {
      setTheme(savedTheme)
    }
    
    const savedLanguage = localStorage.getItem('language')
    if (savedLanguage) {
      language.value = savedLanguage
    }
  }
  
  return {
    // 状态
    loading,
    sidebarCollapsed,
    theme,
    language,
    breadcrumbs,
    
    // 计算属性
    isDarkTheme,
    
    // 操作
    setLoading,
    toggleSidebar,
    setSidebarCollapsed,
    setTheme,
    setLanguage,
    setBreadcrumbs,
    addBreadcrumb,
    clearBreadcrumbs,
    initializeApp
  }
})
